package cn.fl.product.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.fl.capital.constant.CapPayInfoConstant;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.product.service.ISplBankService;
import cn.fl.product.transform.SplBankVOTransform;
import cn.fl.product.vo.SplBankVO;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.spl.facade.spl.api.ISplInfoApiService;
import fl.spl.facade.spl.dto.SplBankDTO;

/**
 * @Description: 供应商开户银行信息表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class SplBankServiceImpl implements ISplBankService {

	/**
	 * 供应商 API 暴露服务
	 */
	@Autowired
	private ISplInfoApiService splInfoApiService;
	
	/**
	 * 本地数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	
	/**
	 * 用户API
	 */
	@Autowired
	private ISysUsrApiService sysUsrApiService;
	
	@Override
	public SplBankVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.newWebLogger("根据主键查询供应商账号信息失败,主键参数为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			throw new BaseException(BaseExceptionConstant.COMMON_0001,BaseExceptionConstant.COMMON_0001_NAME);
		}
		SplBankDTO dto = this.splInfoApiService.selectPrdSplBankById(id, CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
		return SplBankVOTransform.toVO(dto);
	}

	@Override
	public Long add(SplBankVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.newWebLogger("新增供应商账号失败,供应商账号对象参数为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			throw new BaseException(BaseExceptionConstant.COMMON_0001,BaseExceptionConstant.COMMON_0001_NAME);
		}
		return this.splInfoApiService.addPrdSplBank(SplBankVOTransform.toDTO(entity));
	}

	/*@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id))return false;
		return this.prdSplBankApiService.removeById(id);
	}*/

	@Override
	public boolean modify(SplBankVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.newWebLogger("改供应商账号失败,供应商账号对象参数为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			throw new BaseException(BaseExceptionConstant.COMMON_0001,BaseExceptionConstant.COMMON_0001_NAME);
		}
		return this.splInfoApiService.modifyPrdSplBank(SplBankVOTransform.toDTO(entity));
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page){
			page = new Pager();
		}
		page = this.splInfoApiService.searchPrdSplBkListPage(page, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		List<SplBankDTO> resultList = (List<SplBankDTO>) page.getResultList();
		List<SplBankVO> voList = SplBankVOTransform.toVOList(resultList);
		if(CollectionUtils.isNotEmpty(voList)){
			List<Long> usrIds = new ArrayList<Long>();
			for (SplBankVO splBankVO : voList) {
				if(StringUtils.isNotEmpty(splBankVO.getCrtUsrId())){
					usrIds.add(splBankVO.getCrtUsrId());
				}
			}
			if(CollectionUtils.isNotEmpty(usrIds)){
				//设置创建人姓名
				SysUsrQueryCondition qc = new SysUsrQueryCondition();
				qc.setUsrIds(usrIds);
				qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
				List<SysUsrDTO> sysUsrList = this.sysUsrApiService.searchSysUsrList(qc);
				if(CollectionUtils.isNotEmpty(voList) && CollectionUtils.isNotEmpty(sysUsrList)){
					for (SplBankVO prdSplBankVO : voList) {
						for (SysUsrDTO sysUsrDTO : sysUsrList) {
							if(null!=prdSplBankVO.getCrtUsrId() && prdSplBankVO.getCrtUsrId().equals(sysUsrDTO.getId())){
								prdSplBankVO.setCrtUsrNm(sysUsrDTO.getRefRlNm());
								break;
							}
						}
					}
				}
			}
		}
		page.setResultList(voList);
		return page;
	}

	@Override
	public boolean removeByIds(List<Long> ids) throws BaseException {
		if(CollectionUtils.isEmpty(ids)){
			BaseLogUtils.newWebLogger("删除供应商账号失败,主键参数为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			throw new BaseException(BaseExceptionConstant.COMMON_0001,BaseExceptionConstant.COMMON_0001_NAME);
		}
		return this.splInfoApiService.removePrdSplBankByIds(ids);
	}
	
	@Override
	public DataResultDTO addFlowStart(FlowStartParamsDTO flowStartParamsDTO) throws BaseException{
		if(StringUtils.isEmpty(flowStartParamsDTO.getCrtUsrId()) || StringUtils.isEmpty(flowStartParamsDTO.getBusinessKey())){
			BaseLogUtils.newWebLogger("用户ID和业务数据主键必须要存在").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			throw new BaseException(BaseExceptionConstant.COMMON_0001, "用户ID和业务数据主键必须要存在!");
		}
		return this.splInfoApiService.addFlowStart(flowStartParamsDTO);
	}

	@Override
	public List<KeyValueVO> searchBizTypCdList() throws BaseException {
		return this.getKvList(DictionaryConstant.CODE_SPL_BIZ_TYP_CD);
	}
	
	@Override
	public List<KeyValueVO> searchPurpCdList() throws BaseException {
		return this.getKvList(DictionaryConstant.PURP_CD);
	}

    @Override
    public List<KeyValueVO> searchPayeeTypCdList() throws BaseException {
        return this.getKvList(CapPayInfoConstant.CODE_PAYEE_TYP_CD);
    }

	/**
	 * 根据字典中代码组值获取组员集合
	 * @param grpCd 代码组值
	 * @return 集合
	 */
	private List<KeyValueVO> getKvList(String grpCd){
		List<KeyValueVO> kvList = new ArrayList<>();
		try {
			List<SysDictionaryDTO> sysDictionaryDTOList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), grpCd);
			if(CollectionUtils.isNotEmpty(sysDictionaryDTOList)){
				for (SysDictionaryDTO sysDictionaryDTO : sysDictionaryDTOList) {
					KeyValueVO keyValueVO = new KeyValueVO();
					keyValueVO.setKey(sysDictionaryDTO.getCode());
					keyValueVO.setValue(sysDictionaryDTO.getCodeNm());
					kvList.add(keyValueVO);
				}
			}
		} catch (BaseException e) {
			BaseLogUtils.newWebLogger("获取字典项组失败,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(e)
					.warn(LogExceptionEnum.COMMON_CODE_0001);
		} catch (Exception e) {
			BaseLogUtils.newWebLogger("获取字典项组失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(e)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}
		return kvList;
	}
}
